// pages/goods/purchase_goods_detail.js

var WxParse = require('../../utils/wxParse/wxParse.js');
var app = getApp();
var rootDocment = app.globalData.postUrl;
var last_scroll_position = 0
var new_scroll_position = 0
Page({
    /**
     * 页面的初始数据
     * 
     */
    data: {
        user: {},
        rootUrl: rootDocment,
        hiddenLoading: false,
        imgUrls: [],
        indicatorDots: true,
        autoplay: true,
        interval: 5000,
        duration: 1000,
        hasSpec: 0,
        detail: {
            is_vip: false
        },
        isJoin: true,
        showDialog: false,
        spec_price: [],
        spec_list: [],
        amount: 1,
        vip_price: 0,
        price1: 0,
        price: 0,
        stock: 0,
        spec_key: '',
        spec_item: '',
        current_spec: [],
        cartNum: 0,
        currentID: '',
        userInfo: {},
        showShare: false,
        showPic: false,
        sharePic: '',
        roomId: [],
        customParams: '',
        is_write_style: true,
        isIos: true,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this
        wx.getSystemInfo({
            success: function (res) {
                if (res.system.indexOf('Android') > -1) {
                    that.setData({
                        isIos: false
                    })
                }
            }

        })
        //var that = this;
        //初始化
        if (options.id) {
            that.setDetailData(options.id);
        } else {
            var scene = decodeURIComponent(options.scene).split("_");
            that.setDetailData(scene[1]);
            wx.setStorageSync('pid', scene[0]);
        }
        that.setCartData();
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

    //下拉刷新
    onPullDownRefresh: function () {
        var that = this;
        this.setDetailData(that.data.currentID);
        this.setCartData();
        wx.stopPullDownRefresh();
    },
    onPageScroll: function (e) {
        // Do something when page scroll
        //console.log('我动了吗')
        // console.log(e, '滑动');
        var that = this
        let write_style = that.data.write_style
        last_scroll_position = e.scrollTop;
        if (new_scroll_position < last_scroll_position && last_scroll_position > 50) {
            that.setData({
                write_style: 'slideUp'
            })

        } else {
            that.setData({
                write_style: 'slideDown'
            })
        }
        new_scroll_position = last_scroll_position;

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        wx.showLoading({
            title: '加载中',
        })
        var that = this;
        console.log(app.globalData.userInfo, 'app.globalData.userInfo')
        that.setData({
            userInfo: app.globalData.userInfo,
            is_shop: wx.getStorageSync('is_shop'),
            is_vip: wx.getStorageSync('is_vip')
        })

        if (that.data.userInfo.userID == 0) {
            wx.getUserInfo({
                success: function () {
                    that.toLogin();
                }
            })
        } else {
            this.getUserInfo()
        }
    },
    getUserInfo: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['id'] = wx.getStorageSync('user_id3')
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_user/' + paraArr['id'],
            data: {
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                wx.hideLoading()
                console.log(res.data, '1111111111');
                let text = res.data.data.vip_express_time
                if (text == '') {
                    text = '暂未开通'
                } else {
                    text = text.split(" ")[0]
                }
                that.setData({
                    user: res.data.data,
                    isJoin: res.data.data.is_vip
                });
                console.log(that.data.user, 'user')
                wx.setStorageSync('is_vip', res.data.data.is_vip)
            },
            fail: function (res) {
                wx.hideLoading()
            }
        })
    },
    //初始化详情
    setDetailData: function (id) {
        var that = this;
        var has_spec = 0;
        var spec_list = [];
        var paraArr = new Array();
        paraArr['id'] = id;
        paraArr['user_id'] = wx.getStorageSync('user_id3');
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods/' + id,
            data: {
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res.data);
                res.data.is_vip = 1
                var room_id = [res.data.live.room_id];
                var custom_params = encodeURIComponent(JSON.stringify({
                    path: 'pages/goods/detail',
                    id: id
                }))
                WxParse.wxParse('article', 'html', res.data.info, that, 5);
                has_spec = res.data.specPrice.length;
                if (typeof (res.data.specList) != "undefined") spec_list = res.data.specList;
                that.setData({
                    detail: res.data,
                    hiddenLoading: true,
                    imgUrls: res.data.slide,
                    hasSpec: has_spec,
                    spec_price: res.data.specPrice,
                    spec_list: spec_list,
                    price: res.data.price,
                    stock: res.data.stock,
                    currentID: id,
                    roomId: room_id,
                    customParams: custom_params
                });
                //初始化规格
                that.selectSpec();
            }
        })
    },
    //选择规格
    toggleDialog: function () {
        var that = this;
        that.setData({
            showDialog: !that.data.showDialog
        });
    },

    openSpecPopup() {
        this.setData({
            showDialog: true
        });
    },

    closeSpecPopup() {
        this.setData({
            showDialog: false
        });
    },


    //切换规格
    selectSpec: function (e) {
        console.log('调我了呦')
        var that = this;
        console.log(that.data.detail, '22223213213212');
        //如果有规格
        if (that.data.spec_price.length != 0) {
            var spec_list = that.data.spec_list;
            var spec_price = that.data.spec_price;
            var item_arr = new Array();
            var current_arr = {};
            if (typeof (e) == "undefined") { //初始化

                for (var item in spec_list) {
                    item_arr.push(spec_list[item][0]['item_id']);
                    current_arr[item] = spec_list[item][0]['item_id'];
                }
                //获取默认选中规格key
                var spec_key = item_arr.sort(function (a, b) {
                    return a - b
                }).join('_');
                for (var item in spec_price) {
                    if (spec_price[item]['key'] == spec_key) {
                        console.log(that.data.detail.is_vip && that.data.is_vip ? spec_price[item]['vip_price'] : spec_price[item]['price'], 'wwwwwwwwwwwwwww');
                        that.setData({
                            vip_price: spec_price[item]['vip_price'],
                            price: spec_price[item]['price'],
                            price1: that.data.detail.is_vip && that.data.is_shop ? spec_price[item]['hhr_price'] : that.data.is_vip ? spec_price[item]['vip_price'] : spec_price[item]['price'],
                            stock: spec_price[item]['stock'],
                            spec_key: spec_key,
                            spec_item: spec_price[item]['key_name'],
                            current_spec: current_arr
                        });
                        break;
                    }
                }
            } else {
                var current_spec = that.data.current_spec;
                console.log(current_spec, 'current_spec')
                for (var item in spec_list) {
                    console.log(item, e.currentTarget.dataset.spec)
                    if (item == e.currentTarget.dataset.spec) {
                        console.log(e.currentTarget.dataset.id, 'id')
                        item_arr.push(e.currentTarget.dataset.id);
                        current_arr[item] = e.currentTarget.dataset.id;
                    } else {
                        item_arr.push(current_spec[item]);
                        current_arr[item] = current_spec[item];
                    }
                }
                console.log(item_arr, 'item_arr')
                //获取新选中规格key
                var spec_key = item_arr.sort(function (a, b) {
                    return a - b
                }).join('_');
                for (var item in spec_price) {
                    if (spec_price[item]['key'] == spec_key) {
                        that.setData({
                            vip_price: spec_price[item]['vip_price'],
                            price: spec_price[item]['price'],
                            price1: that.data.detail.is_vip && that.data.is_shop ? spec_price[item]['hhr_price'] : that.data.is_vip ? spec_price[item]['vip_price'] : spec_price[item]['price'],
                            stock: spec_price[item]['stock'],
                            spec_key: spec_key,
                            spec_item: spec_price[item]['key_name'],
                            current_spec: current_arr
                        });
                        break;
                    }
                }
            }
        } else {
            this.setData({
                vip_price: that.data.detail.vip_price,
                price: that.data.detail.price,
                price1: that.data.detail.is_vip && that.data.is_shop ? that.data.detail.hhr_price : that.data.is_vip ? that.data.detail.vip_price : that.data.detail.price
            })
        }
    },
    //添加数量
    addAmount: function () {
        var that = this;
        var new_amount = that.data.amount + 1;
        if (new_amount < that.data.stock) {
            that.setData({
                amount: new_amount
            });
        }
    },
    //减少数量
    delAmount: function () {
        var that = this;
        var new_amount = that.data.amount - 1;
        if (new_amount > 0) {
            that.setData({
                amount: new_amount
            });
        }
    },
    //输入数量
    bindKeyInput: function (e) {
        var that = this;
        var amount = Math.round(e.detail.value);
        if (!isNaN(amount) && amount > 0) {
            if (amount > that.data.stock) {
                that.setData({
                    amount: that.data.stock
                });
                return that.data.stock;
            } else {
                that.setData({
                    amount: amount
                });
                return amount;
            }
        } else {
            that.setData({
                amount: 1
            });
            return 1;
        }
    },

    goCouponBtn() {
        wx.navigateTo({
            url: '/pages/user/mycoupon',
        })
    },

    //现在购买
    buyNow: function () {
        var that = this;
        if (that.data.userInfo.userID > 0) {
            app.redirect('order/index', 'goods_id=' + that.data.detail['id'] + '&spec_key=' + that.data.spec_key + '&amount=' + that.data.amount);
        } else {
            that.setData({
                showDialog: false
            });
            wx.showModal({
                title: '请先登录',
                content: '确定登录？',
                success(res) {
                    if (res.confirm) {
                        that.toLogin();
                    }
                }
            })
        }
    },

    //加入购物车
    addCart: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['goods_id'] = that.data.detail['id'];
        paraArr['spec_key'] = that.data.spec_key;
        paraArr['amount'] = that.data.amount;
        paraArr['user_id'] = that.data.userInfo.userID;
        paraArr['type'] = 1;

        if (paraArr['user_id'] > 0) {
            var sign = app.signature(paraArr);
            wx.request({
                url: rootDocment + '/api_cart',
                data: {
                    goods_id: paraArr['goods_id'],
                    spec_key: paraArr['spec_key'],
                    key_name: that.data.spec_item,
                    amount: paraArr['amount'],
                    user_id: paraArr['user_id'],
                    type: paraArr['type'],
                    sign: sign
                },
                method: 'POST',
                header: {},
                success: function (res) {
                    console.log(res.data);
                    that.setData({
                        showDialog: false
                    });
                    if (res.data.code == '1001') {
                        that.setCartData();
                        wx.showToast({
                            title: '添加成功',
                        })
                    } else {
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none'
                        })
                    }
                }
            })
        } else {
            that.setData({
                showDialog: false
            });
            wx.showModal({
                title: '请先登录',
                content: '确定登录？',
                success(res) {
                    if (res.confirm) {
                        that.toLogin();
                    }
                }
            })
        }
    },
    //分享
    toggleShare: function () {
        var that = this;
        that.setData({
            showShare: !that.data.showShare
        });
    },
    //获取分享图
    getPic: function () {
        var that = this;
        if (that.data.showPic) {
            that.setData({
                showPic: !that.data.showPic
            });
        } else {
            that.setData({
                showShare: false,
                hiddenLoading: false
            });
            var m_page = 'pages/goods/detail';
            var m_scene = that.data.userInfo.userID + '_' + that.data.currentID;
            var paraArr = new Array();
            paraArr['page'] = m_page;
            paraArr['scene'] = m_scene;
            var sign = app.signature(paraArr);
            wx.request({
                url: rootDocment + '/api/get_qrcode',
                data: {
                    page: m_page,
                    scene: m_scene,
                    sign: sign
                },
                method: 'GET',
                header: {},
                success: function (res) {
                    console.log(res.data.msg);
                    if (res.data.success == true) {
                        that.setData({
                            showPic: !that.data.showPic,
                            sharePic: res.data.msg,
                            hiddenLoading: true
                        });
                    }
                }
            })
        }
    },
    //保存分享图片
    savePic: function () {
        var that = this;
        wx.downloadFile({
            url: that.data.rootUrl + that.data.sharePic,
            success: function (res) {
                let path = res.tempFilePath
                wx.saveImageToPhotosAlbum({
                    filePath: path,
                    success(res) {
                        wx.showToast({
                            title: '保存成功'
                        })
                    },
                    fail(res) {
                        wx.showToast({
                            title: '保存失败'
                        })
                    },
                    complete(res) {
                        that.setData({
                            showPic: false
                        });
                    }
                })
            },
            fail: function (res) {
                console.log(res)
            }
        })

    },

    //去登录
    toLogin: function () {
        var that = this;
        //用户授权登录
        app.login(function (userInfo) {
            that.getUserInfo()
            that.setData({
                userInfo: userInfo
            });
            wx.showToast({
                title: '登录成功',
                icon: 'none'
            })
        });
    },

    //获取购物车列表
    setCartData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['user_id'] = that.data.userInfo.userID;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_cart',
            data: {
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    cartNum: res.data.length
                });
            }
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        console.log(res);
        var that = this;
        return {
            title: that.data.detail['title'],
            path: '/pages/goods/detail?scene=' + that.data.userInfo.userID + '_' + that.data.currentID
        }
    },

    onShareTimeline: function (res) {
        console.log(res);
        var that = this;
        return {
            title: that.data.detail['title'],
            path: '/pages/goods/detail?scene=' + that.data.userInfo.userID + '_' + that.data.currentID,
            imageUrl: that.data.detail['pic']
        }
    }


})